//
//  ZXY_ScanVC.m
//  Lover_BridgeiOS
//
//  Created by 宇周 on 15/11/18.
//  Copyright © 2015年 宇周. All rights reserved.
//

#import "ZXY_ScanVC.h"
#import "ZXY_IMGFlashHelper.h"

@interface ZXY_ScanVC ()<AVCaptureMetadataOutputObjectsDelegate>
@property (weak, nonatomic) IBOutlet UIView *viewPreview;
@property (nonatomic , strong)ZXY_IMGFlashHelper *flashHelper;   //动画效果

//捕捉会话
@property(nonatomic , strong)AVCaptureSession *captureSession; //摄像机session
//展示layer
@property(nonatomic , strong)AVCaptureVideoPreviewLayer *videoPreviewLayer;
@property(nonatomic , strong)UIView *boxView;
@property(nonatomic , assign)CGFloat spaceRadio;

@end

@implementation ZXY_ScanVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.spaceRadio = 0.2;
    [self startScan];
    [self setThisView];
    // Do any additional setup after loading the view.
}

- (void)setThisView
{
    [self setLeftNaviItem:@"backArrow"];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/**
 *  扫描开始
 */
- (void)startScan
{
    NSError *error;
    AVCaptureDevice *captureDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo]; //使用视频类型
    AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:captureDevice
                                                                        error:&error]; //为input 增加device
    //出现错误
    if(!input)
    {
        NSLog(@"ERROR IS %@",error);
        return;
    }
    
    AVCaptureMetadataOutput *output = [[AVCaptureMetadataOutput alloc] init]; //配置output
    _captureSession = [[AVCaptureSession alloc] init];   //设置扫描session
    [_captureSession addInput:input];
    [_captureSession addOutput:output];
    _captureSession.sessionPreset = AVCaptureSessionPreset1920x1080;  //设置分辨率（默认为扫描为横屏幕显示）
    dispatch_queue_t dispathQueue;  //另起线程
    dispathQueue = dispatch_queue_create("myQueue" , NULL);
    [output setMetadataObjectsDelegate:self queue:dispathQueue]; //设置代理
    [output setMetadataObjectTypes:@[AVMetadataObjectTypeQRCode]]; //设置处处类型为 QRCode 二维码
    _videoPreviewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:_captureSession];  //设置layer
    [_videoPreviewLayer setVideoGravity:AVLayerVideoGravityResizeAspectFill];
    [_videoPreviewLayer setFrame:self.view.layer.bounds];
    [self.view.layer addSublayer:_videoPreviewLayer];
    
    CGSize vSize = self.view.frame.size;
    CGFloat width = vSize.width;
    CGFloat reWidth = width * (1-2*self.spaceRadio);
    
    CGFloat radioHeight = reWidth/vSize.height ;
    
    CGFloat radioOfScreen = vSize.width / vSize.height;
    
    if(radioOfScreen < 1)   //竖屏下
    {
        //设置扫描区域
        output.rectOfInterest = CGRectMake(self.spaceRadio, self.spaceRadio,  radioHeight , 1-self.spaceRadio*2);
    }
    else //横屏下
    {
        output.rectOfInterest = CGRectMake(self.spaceRadio, self.spaceRadio,  1-self.spaceRadio*2,radioHeight  );
    }
    
    //为扫描区域增加边框
    CGFloat boxOriginX = vSize.width * self.spaceRadio;
    CGFloat boxOriginY = vSize.height * self.spaceRadio;
    CGFloat boxWidth   = vSize.width * (1 - self.spaceRadio * 2);
    
    _boxView = [[UIView alloc] initWithFrame:CGRectMake(boxOriginX,boxOriginY, boxWidth, boxWidth)];
    _boxView.layer.borderColor = [UIColor greenColor].CGColor;
    _boxView.layer.borderWidth = 1.0f;
    
    //增加闪动动画
    _flashHelper = [[ZXY_IMGFlashHelper alloc] init];
    [_flashHelper setFlashImg:_boxView];
    [_flashHelper startFlash];
    [self.view addSubview:_boxView];
    
    //增加灰色背景
    [self drawBackGray];
    
    //扫面线
    [self drawLineLayer];
    //开始扫描
    [_captureSession startRunning];
}

/**
 *  画扫描线并且增加动画
 */
- (void)drawLineLayer
{
    CGSize vSize = self.view.frame.size;
    
    CGFloat boxOriginX = vSize.width * self.spaceRadio;
    CGFloat boxOriginY = vSize.height * self.spaceRadio;
    CGFloat boxWidth   = vSize.width * (1 - self.spaceRadio * 2);
    CALayer *anL       = [CALayer layer];
    UIImage *lineImg   = [UIImage imageNamed:@"scan_line"];
    anL.contents       = (__bridge id _Nullable)(lineImg.CGImage);
    anL.frame = CGRectMake(boxOriginX, boxOriginY + 10, boxWidth, 1);
    [self.view.layer addSublayer:anL];
    anL.anchorPoint = CGPointMake(0, 0); //默认anchor在中间
    NSValue *fromVa = [NSValue valueWithCGPoint:CGPointMake(boxOriginX , boxOriginY)];
    NSValue *toVa   = [NSValue valueWithCGPoint:CGPointMake(boxOriginX , boxOriginY + boxWidth)];
    
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"position"];
    animation.fromValue = fromVa;
    animation.toValue   = toVa;
    animation.duration  = 2;
    animation.repeatCount = HUGE_VALF;
    animation.autoreverses = YES;
    animation.removedOnCompletion = NO;
    [anL addAnimation:animation forKey:@"lalaKey"];
    
}


/**
 *  添加扫描区域外的黑色背景，增加四个layer
 */
- (void)drawBackGray
{
    CGSize vSize = self.view.frame.size;
    CGFloat width = vSize.width;
    CGFloat remainSpaceRadio = (1 - self.spaceRadio * 2) ;
    
    
    CGRect leftFrame = CGRectMake(0, 0, self.spaceRadio*width, vSize.height);
    CGRect topFrame  = CGRectMake(self.spaceRadio*width, 0, remainSpaceRadio*width, self.spaceRadio*vSize.height);
    CGRect rightFrame = CGRectMake((1-self.spaceRadio)*width, 0, self.spaceRadio*width, vSize.height);
    CGRect bottomFrame = CGRectMake(self.spaceRadio*width,   remainSpaceRadio*width + self.spaceRadio*vSize.height, remainSpaceRadio*width, vSize.height - remainSpaceRadio*width - self.spaceRadio*vSize.height);
    [self drawPath:leftFrame];
    [self drawPath:topFrame];
    [self drawPath:rightFrame];
    [self drawPath:bottomFrame];
}

- (void)drawPath:(CGRect)drawRect
{
    CAShapeLayer *shapeLayer = [CAShapeLayer layer];
    shapeLayer.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.7].CGColor;
    shapeLayer.frame = drawRect;
    [self.view.layer addSublayer:shapeLayer];
}

//扫描结束
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection
{
    if(metadataObjects != nil && [metadataObjects count] > 0)
    {
        AVMetadataMachineReadableCodeObject *metadata = [metadataObjects objectAtIndex:0];
        if([[metadata type] isEqualToString:AVMetadataObjectTypeQRCode])
        {
            [self performSelectorOnMainThread:@selector(scanFinish:) withObject:metadata.stringValue waitUntilDone:NO];
            [_captureSession stopRunning];
        }
    }
}

- (void)scanFinish:(NSString *)data
{
    [_flashHelper stopFlash];
    NSLog(@"data is %@",data);
    if(self.scanSuccess != nil)
    {
        self.scanSuccess(data);
    }
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
